package com.sinoglobal.ningxia.fragment;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.TextView;

import com.ab.view.listener.AbOnListViewListener;
import com.ab.view.pullview.AbPullListView;
import com.sinoglobal.ningxia.R;
import com.sinoglobal.ningxia.activity.mico.ProgramInfoActivity;
import com.sinoglobal.ningxia.activity.vip.Login;
import com.sinoglobal.ningxia.adapter.NoImgCommentAdapter;
import com.sinoglobal.ningxia.beans.CommentIdVo;
import com.sinoglobal.ningxia.beans.CommentInfoVo;
import com.sinoglobal.ningxia.beans.CommentListVo;
import com.sinoglobal.ningxia.beans.CommentSubmitVo;
import com.sinoglobal.ningxia.downdata.imp.RemoteImpl;
import com.sinoglobal.ningxia.frame.FlyApplication;
import com.sinoglobal.ningxia.http.Code;
import com.sinoglobal.ningxia.thread.ItktAsyncTaskWithDialog;
import com.sinoglobal.ningxia.utils.FlyUtil;
import com.sinoglobal.ningxia.utils.ItktLog;
import com.sinoglobal.ningxia.utils.TextUtil;
import com.sinoglobal.ningxia.utils.ToastBuilder;

import java.text.MessageFormat;
import java.util.ArrayList;

/**
 * @author qiwx
 * @createdate 2014-6-26 下午1:56:46
 * @Description: 节目评论
 */
public class ProgramCommentFragment extends Fragment implements
		AbOnListViewListener, OnClickListener {
	private View view;// 频道view
	private ArrayList<CommentInfoVo> listData;
	private AbPullListView commentList;
	private TextView noData;// 当没有数据时展示
	NoImgCommentAdapter adapter;
	AsyncTask<String, Void, CommentListVo> mTask; // 评论
	private String programType = "2";// 栏目类型
	private byte limt1 = 0;// 请求页数
	private byte limt2;// 请求条数，此值默认给个0
	private String programId;// 栏目id
	private boolean reFresh = false;// 刷新评论
	private ImageView submit;// 提交评论
	private EditText content;// 评论内容
	ItktAsyncTaskWithDialog<Void, Void, CommentIdVo> commentTask;
	private String commentType = "2";
	private static Context mContext;
	private ProgressBar pb;
	private RadioButton rb;

	public static ProgramCommentFragment getIntance(Context context, String id) {
		ProgramCommentFragment fragment = new ProgramCommentFragment();
		Bundle bundle = new Bundle();
		bundle.putString("id", id);
		fragment.setArguments(bundle);

		mContext = context;

		return fragment;

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle args = getArguments();
		if (args != null)
			programId = args.getString("id");
		listData = new ArrayList<CommentInfoVo>();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		view = LayoutInflater.from(mContext).inflate(R.layout.refresh_list,
				null);
		init();
		loadData();
		return view;
	}

	private void init() {
		// listData = new ArrayList<CommentInfoVo>();
		/*
		 * for (int i = 0; i < 5; i++) { CommentInfoVo bean = new
		 * CommentInfoVo(); bean.setNickname("小明");
		 * bean.setContent("很好很好很好很好很好"); bean.setCreate_time("2014-08-12");
		 * listData.add(bean); }
		 */
		pb = (ProgressBar) view.findViewById(R.id.programHistory);
		submit = (ImageView) view.findViewById(R.id.comment_submit);
		submit.setOnClickListener(this);
		content = (EditText) view.findViewById(R.id.comment_content);
		content.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {

				InputMethodManager imm = (InputMethodManager) getActivity()
						.getSystemService(Context.INPUT_METHOD_SERVICE);
				if (imm.isActive()) {
					ProgramInfoActivity.hideRb();
				}
				return false;

			}
		});
		noData = (TextView) view.findViewById(R.id.noData);
		commentList = (AbPullListView) view.findViewById(R.id.refreshList);
		commentList.getHeaderView().setHeaderProgressBarDrawable(
				this.getResources().getDrawable(R.drawable.progress_circular));
		commentList.getFooterView().setFooterProgressBarDrawable(
				this.getResources().getDrawable(R.drawable.progress_circular));
		commentList.setAbOnListViewListener(this);

	}

	private void loadData() {
		pb.setVisibility(View.VISIBLE);
		mTask = new ItktAsyncTaskWithDialog<String, Void, CommentListVo>(
				getString(R.string.data_loading), true, false) {

			@Override
			public CommentListVo before(String... params) throws Exception {

				CommentListVo vo;

				try {
					vo = RemoteImpl.getInstance().getCommentList(params[0],
							Byte.parseByte(params[1]),
							Byte.parseByte(params[2]),
							Byte.parseByte(params[3]));
				} catch (Exception e) {
					e.printStackTrace();

					vo = null;
				}
				return vo;
			}

			@Override
			public void after(CommentListVo result) {
				if (null == result) {
					return;
				}
				pb.setVisibility(View.GONE);
				if (null != result) {
					int code = result.getCode();
					switch (code) {
					case Code.CODE_SUCCESS:
						if (reFresh)
							listData.clear();
						if (result.getList().size() <= 0
								|| null == result.getList()) {
							return;
						}
						listData.addAll(result.getList());
						ItktLog.i("=====listData.size()====" + listData.size());
						if (adapter == null) {
							try {
								adapter = new NoImgCommentAdapter(
										getActivity(), listData);
							} catch (Exception e) {
								e.printStackTrace();
							}
						} else {
							adapter.notifyDataSetChanged();
						}
						if (null == adapter) {
							return;
						}
						commentList.setAdapter(adapter);
						noData.setVisibility(View.GONE);
						commentList.stopRefresh();
						commentList.setPullLoadEnable(true);
						break;
					case Code.CODE_NODATA:
						if (listData.size() == 0)
							noData.setVisibility(View.VISIBLE);
						else {
							commentList.setPullLoadEnable(false);
							ToastBuilder.getIntance(FlyApplication.context).showToast(
									getString(R.string.noMoreMessage));
							commentList.stopLoadMore();
						}
						break;
					}
				}
				reFresh = false;

				cancel(true);
			}

			@Override
			public void exception() {
				commentList.setPullRefreshEnable(true);
				commentList.setPullLoadEnable(true);
				pb.setVisibility(View.GONE);
			}

		};
		mTask.execute(programId, programType, String.valueOf(limt1),
				String.valueOf(limt2));
	}

	@Override
	public void onRefresh() {
		// 刷新机制暂时不做限制，
		limt1 = 0;
		reFresh = true;
		loadData();
	}

	@Override
	public void onLoadMore() {
		++limt1;
		loadData();
		// mTask.execute(programId, programType, String.valueOf(++limt1),
		// String.valueOf(limt2));
	}

	private void sendComment(final String comment) {

		commentTask = new ItktAsyncTaskWithDialog<Void, Void, CommentIdVo>(
				getString(R.string.loading), true, true) {

			@Override
			public void exception() {

			}

			@Override
			public CommentIdVo before(Void... params) throws Exception {
				return RemoteImpl.getInstance()
						.submitComment(
								new CommentSubmitVo(0, comment, programId,
										commentType), getActivity());
			}

			@Override
			public void after(CommentIdVo result) {
				if (result.getCode() == Code.CODE_SUCCESS) {
					onRefresh();
					ToastBuilder.getIntance(FlyApplication.context).showToast(
							getResources().getString(R.string.commentSuccess));
					content.setText(null);
				} else {
					ToastBuilder.getIntance(FlyApplication.context).showToast(
							result.getMessage());
					content.setText(null);
				}

			}
		};
		commentTask.execute();

	}

	/**
	 * @author qiwx
	 * @createdate 2014-7-21 上午9:53:30
	 * @Description:
	 * @type
	 * @throws Exception
	 * @parameters
	 */
	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.comment_submit:
			if (TextUtil.stringIsNull(FlyApplication.userId)) {
				FlyUtil.intentForward(getActivity(), Login.class);
				return;
			}
			String mContent = content.getText().toString().trim();
			if (TextUtil.stringIsNull(mContent)) {
				
				ToastBuilder.getIntance(FlyApplication.context).showToast(
						getString(R.string.no_content_comment));
				return;
			}
			if (mContent.length() > 50) {
				String info = getString(R.string.commentInfo);
				info = MessageFormat.format(info, mContent.length());
				ToastBuilder.getIntance(FlyApplication.context).showToast(info);
				return;
			}
			sendComment(mContent);
			break;
		}
	}

}
